//
//  ViewController.m
//  RL_项目二
//
//  Created by rimi on 16/3/15.
//  Copyright © 2016年 ruifengpeixun. All rights reserved.
//

#import "ViewController.h"
#import "TableViewCell.h"
#import "FitOfScreen.h"
#import "BootViewController.h"
#import "ChartViewController.h"
#import "LocationViewController.h"
#import "WeatherDataRequest.h"
#import "CityPickerView.h"
#import "loadView.h"
#import "AnimationViewController.h"
#import <CoreLocation/CoreLocation.h>

#define SCREEN_WIDTH self.view.frame.size.width
#define SCREEN_HEIGHT self.view.frame.size.height

#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
#define DIC_TITLEDETAIL @"titleDetail"

static NSString *cellIdentifer = @"cellIdentifer";

@interface ViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource,CLLocationManagerDelegate>

@property (nonatomic , assign) BOOL isOut;
@property (nonatomic , assign) BOOL language;
@property (nonatomic , strong) NSString *cityName;
@property (nonatomic , strong) UIButton *location;
@property (nonatomic , strong) UILabel *weatherLab;
@property (nonatomic , strong) NSString *locationCity;
@property (nonatomic , strong) UITextField *position;
@property (nonatomic , strong) UITableView *tableView;
@property (nonatomic , strong) UIScrollView * scrollView;
@property (nonatomic , strong) UITapGestureRecognizer *tap;
@property (nonatomic , strong) CLLocationManager *locationManager;
@property (nonatomic , strong) LocationViewController *locationVC;
@property (nonatomic , strong) AnimationViewController *weatherView;
@property (nonatomic , strong) ChartViewController *lineChart;
@property (nonatomic , strong) UIPanGestureRecognizer *pan;
@property (nonatomic , strong) NSMutableArray *titleArray;
@property (nonatomic , strong) NSMutableArray *textArray;
@property (nonatomic , strong) NSMutableArray *DataArray;
@property (nonatomic , strong) CityPickerView *pickView;
@property (nonatomic , strong) NSDictionary *DataDic;
@property (nonatomic , strong) NSDictionary *AQIDic;
@property (nonatomic , strong) NSString *AQIlevel;
@property (nonatomic , strong) UIButton *refresh;
@property (nonatomic , strong) UIView *lastView;
@property (nonatomic , strong) loadView *goTo;
@property (nonatomic , assign) BOOL isFristLoca;
@property (nonatomic , strong) UIView *mask;
@end

@implementation ViewController

- (NSMutableArray *)titleArray {

    if (!_titleArray) {
        _titleArray = [[NSMutableArray alloc]init];
    }
    return  _titleArray;
}

- (NSMutableArray *)textArray {
    
    if (!_textArray) {
        _textArray = [[NSMutableArray alloc]init];
    }
    return  _textArray;
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self httpRequst:_city];
    [self initLocationDataSource];

}

- (UIView *)lastView {
    if (!_lastView) {
        _lastView = [[UIView alloc]initWithFrame:LRLCGRectMake(90, -35 , 200, 35)];
        _position = [[UITextField alloc]initWithFrame:LRLCGRectMake(0, 0, 100, 35)];
        _position.borderStyle = UITextBorderStyleNone;
        _position.keyboardType = UIKeyboardTypeWebSearch;
        _position.keyboardAppearance=UIKeyboardAppearanceAlert;
        _position.backgroundColor =[UIColor clearColor];
        _position.font = [UIFont fontWithName:@"FZHTK--GBK1-0" size:LRLRadioWidth * 13];
        _position.textAlignment = NSTextAlignmentCenter;
        _position.textColor = [UIColor whiteColor];
        _position.tintColor = [UIColor blackColor];
        _position.enabled = NO;
        _position.text = @"天津-天津";
        _position.returnKeyType = UIReturnKeyDone;
        [_lastView addSubview:_position];
        UIView *view1 = [[UIView alloc]initWithFrame:LRLCGRectMake(0, 33, 110, 1)];
        view1.backgroundColor = [UIColor whiteColor];
        [_lastView addSubview:view1];
        _goTo = [[loadView alloc]initWithFrame:LRLCGRectMake(120, 0, 35, 35)];
        [_goTo addTarget:self action:@selector(goToBtn:) forControlEvents:UIControlEventTouchUpInside];
        [_lastView addSubview:_goTo];
        
    }
    return _lastView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH , SCREEN_HEIGHT *1.31 );
        _scrollView.pagingEnabled = NO;
        _scrollView.bounces = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.alwaysBounceVertical = YES;
        _scrollView.delegate = self;
       
    }
    return _scrollView;
}

- (UILabel *)weatherLab {
    if (!_weatherLab) {
        _weatherLab = [[UILabel alloc]init];
        _weatherLab.center = LRLCGPointMake(160, 168);
        _weatherLab.bounds = LRLCGRectMake(0, 0, 320, 15);
        _weatherLab.font = [UIFont boldSystemFontOfSize:14];
        _weatherLab.font = [UIFont fontWithName:@"FZHTK--GBK1-0" size:14 * LRLRadioWidth];
        _weatherLab.textColor = [UIColor colorWithRed:0.149 green:0.149 blue:0.149 alpha:1.0];
        _weatherLab.textAlignment = NSTextAlignmentCenter;
        _weatherLab.lineBreakMode = NSLineBreakByTruncatingMiddle;

    }
    return _weatherLab;
}

- (UIButton *)location {
    if (!_location) {
        _location = [UIButton buttonWithType:UIButtonTypeCustom];
        _location.bounds = LRLCGRectMake(0, 0, 30, 30);
        _location.center = LRLCGPointMake(160, -30);
        [_location setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
        [_location addTarget:self action:@selector(locationBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _location;
}

- (AnimationViewController *)weatherView {
    if (!_weatherView) {
        _weatherView = [[AnimationViewController alloc]init:_city];
        _weatherView.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 3);
        _weatherView.view.backgroundColor = [UIColor whiteColor];
        _weatherView.view.alpha = 0.95;
        _refresh = [[UIButton alloc]initWithFrame:LRLCGRectMake(290, 30, 15, 15)];
        [_refresh setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
        [_refresh addTarget:self action:@selector(refreshTaped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _weatherView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 , SCREEN_WIDTH, SCREEN_HEIGHT / 3 *1.95);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = round(SCREEN_HEIGHT / 9.5);
        _tableView.scrollEnabled =NO;
        _tableView.alpha = 0.95;

    }
    return _tableView;
}

- (UIPanGestureRecognizer *)pan {
    if (!_pan) {
        _pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(respondsToPan:)];
    }
    return _pan;
}

- (UITapGestureRecognizer *)tap {
    if (!_tap) {
        _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(respondsToTap:)];
    }
    return _tap;
}

- (ChartViewController *)lineChart {
    if (!_lineChart) {
        _lineChart = [[ChartViewController alloc]init:_city];
    }
    return _lineChart;

}

#pragma mark - tableView & weatherView 初始化数据
- (void)initDataSource

{
    //tableViewData
    _DataArray=[[NSMutableArray alloc] init];
    NSArray *titleArrays = @[@"感冒指数",@"空调指数",@"穿衣指数",@"运动指数",@"紫外线指数",@"污染指数",@"洗车指数"];
 
    for (int i=0;i<self.titleArray.count ;i++) {
        
        NSMutableArray *array = [[NSMutableArray alloc] init];
        NSString *string = self.textArray[i];
        [array addObject:string];
        /**创建一个字典 包含数组，分组名，是否展开的标示*/
        NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithObjectsAndKeys:array,DIC_ARARRY,titleArrays[i],DIC_TITILESTRING,[NSNumber numberWithInt:0],DIC_EXPANDED,self.titleArray[i],DIC_TITLEDETAIL,nil];
        if (i == self.titleArray.count - 1 ) {
            [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
        }
        /**将字典加入数组*/
        [_DataArray addObject:dic];
        
        
    }
        
    //weatherViewData
    /**当下时间*/
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd"];
    NSString *currentTime = [formatter stringFromDate:[NSDate date]];
    /**位置*/
    if (_city.length < 1) {
        _city = @"beijing";
    }
    _city = _city.uppercaseString;
    /**AQI*/
    NSLog(@"levellevellevellevellevel%@",self.AQIDic[@"level"]);
       int level = 0;
    if (![self.AQIDic[@"level"] isKindOfClass:[NSNull class]]){
         level = [self.AQIDic[@"level"] intValue];
    }
    if (level == 0){
        _AQIlevel = @"无";
    }else if (level <= 1) {
        _AQIlevel = @"优";
    }else if (level == 2){
        _AQIlevel = @"良";
    }else {
        _AQIlevel = @"差";
    }
    
    self.weatherLab.text = [NSString stringWithFormat:@"%@ %@ AQI %@ %@",currentTime,_city,self.AQIDic[@"curPm"],_AQIlevel];
    [_tableView reloadData];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDataSource];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backImage"]];
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.location];
    [self.scrollView addSubview:self.weatherView.view];
    [self.scrollView addSubview:self.lineChart.view];
    [self.scrollView addSubview:self.tableView];
    [self.weatherView.view addSubview:self.weatherLab];
    [self.scrollView addSubview:_refresh];
    [self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:cellIdentifer];
    [UIView animateWithDuration:0.3 animations:^{
        
        self.tableView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 * 2 - 40, SCREEN_WIDTH, SCREEN_HEIGHT / 3 *2);
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:1
                              delay:0
             usingSpringWithDamping:0.3
              initialSpringVelocity:0.8
                            options:0
                         animations:^{
                             self.tableView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 * 2 , SCREEN_WIDTH, SCREEN_HEIGHT / 3 *2);
                             
                         }
                         completion:nil];
    }];


}


#pragma mark - BUTTON的响应事件
/**刷新Button的响应事件*/
- (void)refreshTaped:(UIButton *)sender {
    [self.lineChart InitDataSource:_city];
    [self httpRequst:_city];
    [self.weatherView httpRequst:_city];
}

/**添加城市的响应事件*/
- (void)locationBtn:(UIButton *)sender {
    _locationVC = [[LocationViewController alloc]init];
    [self performSelector:@selector(duang) withObject:nil afterDelay:0.5];
    
    self.pickView = [[CityPickerView alloc] initWithFrame:LRLCGRectMake(0, 568 , 320, 205)];
    
    [UIView animateWithDuration:1.7 animations:^{
      
       self.scrollView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
       self.scrollView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 + 28 * LRLRadioWidth, SCREEN_WIDTH, SCREEN_HEIGHT);
       self.pickView.frame = LRLCGRectMake(0, 363 , 320, 205);
        
   }];

}

/**添加城市按钮响应事件的延迟调用事件*/
- (void)duang {
    
    [self.view addSubview:_locationVC.view];
    _position.text = @"天津-天津";
    [self.view addSubview:self.lastView];
    [UIView animateWithDuration:1 animations:^{
        self.lastView.frame = LRLCGRectMake(90, 160 , 200, 35);
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5
                              delay:0
             usingSpringWithDamping:0.3
              initialSpringVelocity:1
                            options:0
                         animations:^{
                             self.lastView.frame = LRLCGRectMake(90,180,200, 35);
                         }
                         completion:nil];
    }];
    
    self.pickView.backgroundColor = [UIColor blackColor];
    self.pickView.delegate = self;
    [self.view addSubview:self.pickView];


}

/**定位输入框按钮的响应事件*/
- (void)goToBtn:(UIButton *)sender {
   
    /***如果输入框内的值不为空，将输入框的值传入*/
    _city = [self.pickView.proviceDictionary objectForKey:@"county"];
   
    [UIView animateWithDuration:0.5 animations:^{
        
        self.scrollView.frame = CGRectMake(0, 0 , SCREEN_WIDTH, SCREEN_HEIGHT);
        _locationVC.view.frame = CGRectMake(0, -SCREEN_HEIGHT , SCREEN_WIDTH, SCREEN_HEIGHT);
       self.pickView.frame = LRLCGRectMake(0, 568 , 320, 205);
       self.lastView.frame = LRLCGRectMake(90,-35,200, 35);

    } completion:^(BOOL finished) {
        [_mask removeFromSuperview];
        [self.lineChart InitDataSource:_city];
        [_locationVC.view removeFromSuperview];
        [self.pickView removeFromSuperview];
        [self.lastView removeFromSuperview];
        [self httpRequst:_city];
        [self.weatherView httpRequst:_city];
//        
    }];

}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{
    
    return _DataArray.count ;
  
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        
        return array.count;
    
    }else
        
    {
        
        return 0;
    
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer forIndexPath:indexPath];
    if (!cell) {
        
        cell = [[TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
    }
    NSArray *array=[[_DataArray objectAtIndex:indexPath.section] objectForKey:DIC_ARARRY];
        cell.text.text=[array objectAtIndex:indexPath.row];
    
    return cell;
    
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{
    /**创建新视图*/
    UIView *hView = [[UIView alloc]initWithFrame:LRLCGRectMake(0,0, 320, 43.5)];
    hView.backgroundColor=[UIColor whiteColor];
    
    /**创建可点击的按钮*/
    UIButton* eButton = [[UIButton alloc] init];
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
   
    if ([self isExpanded:section]){
        [eButton setImage: [ UIImage imageNamed: @"btn_up" ]forState:UIControlStateNormal];
    }
    else{
        [eButton setImage: [ UIImage imageNamed: @"btn_down" ]forState:UIControlStateNormal];
    }
    
    [eButton setTitle:[[_DataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    [eButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5 *LRLRadioHeight, 0, 0)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(0, 295 *LRLRadioHeight, 0, 0)];
   

    eButton.titleLabel.font = [UIFont fontWithName:@"FZHTK--GBK1-0" size:13 * LRLRadioWidth];

    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    eButton.frame = hView.frame;
    eButton.tag = section;
    
    [hView addSubview:eButton];
    
    /**创建显示详情的文本*/

    UILabel *label = [[UILabel alloc]initWithFrame:LRLCGRectMake(147, 13, 135, 16)];
    label.font = [UIFont fontWithName:@"FZHTK--GBK1-0" size:13 * LRLRadioWidth];

    label.text = [[_DataArray objectAtIndex:section] objectForKey:DIC_TITLEDETAIL];
    label.textAlignment = NSTextAlignmentRight;
    [hView addSubview:label];

    return hView;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{
    
    return SCREEN_HEIGHT / 13;
    
}

#pragma mark - tableView 判断折叠 内部调用

//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(NSInteger)section{
    
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    
    if (expanded) {
        
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
        CGRect tableFrame = self.tableView.frame;
        self.tableView.frame = CGRectMake(0, SCREEN_HEIGHT / 3*2 ,SCREEN_WIDTH,tableFrame.size.height - round(SCREEN_HEIGHT / 9.5));
        self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH , tableFrame.size.height + SCREEN_HEIGHT /3*2 - round(SCREEN_HEIGHT / 9.5) );

    }else
        
    {
        
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
        CGRect tableFrame = self.tableView.frame;
        self.tableView.frame = CGRectMake(0, SCREEN_HEIGHT / 3*2 ,SCREEN_WIDTH,tableFrame.size.height + round(SCREEN_HEIGHT / 9.5));
        self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH , tableFrame.size.height + SCREEN_HEIGHT /3*2 + round(SCREEN_HEIGHT / 9.5) );
        
    }
    
}

//返回指定节是否是展开的
-(int)isExpanded:(NSInteger)section{
    
    NSDictionary *dic=[_DataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    
    return expanded;
    
}


//按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    
    UIButton* btn= (UIButton*)sender;
    NSInteger section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    
    [_tableView reloadData];
    
}

#pragma mark - scrollViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    if (scrollView.contentOffset.y < - 40*LRLRadioWidth) {
    
        _isOut=YES;
        
    }else {
    
        _isOut=NO;
    }
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if (scrollView.contentOffset.y < - 40*LRLRadioWidth) {
        [UIView animateWithDuration:0.5 animations:^{
            
            scrollView.contentInset = UIEdgeInsetsMake(0, 0.0f, 0.0f, 0.0f);


        }];
    }
    
    if (_isOut) {
      
        [UIView animateWithDuration:0.3 animations:^{
        
            scrollView.contentInset = UIEdgeInsetsMake(60*LRLRadioWidth, 0.0f, 0.0f, 0.0f);
            _mask = [[UIView alloc]initWithFrame:LRLCGRectMake(0, 60, 320, 508)];
            [self.view addSubview:_mask];
            [_mask addGestureRecognizer:self.tap];
            _isOut=NO;
        }];
    }
}

#pragma mark - 手势action

- (void)respondsToTap:(UITapGestureRecognizer *)sender {
    [_mask removeGestureRecognizer:self.tap];
    [_mask removeFromSuperview];
    [UIView animateWithDuration:0.3 animations:^{
     
        self.scrollView.contentInset = UIEdgeInsetsMake(0, 0.0f, 0.0f, 0.0f);
        
    } completion:nil];
    
}

- (void)respondsToPan:(UIPanGestureRecognizer *)sender {

}

- (void) updateLabel {
    _position.text = [self.pickView.proviceDictionary objectForKey:@"city"];
    _position.text = [NSString stringWithFormat:@"%@-%@",_position.text,[self.pickView.proviceDictionary objectForKey:@"county"]];

}

- (void)httpRequst:(NSString *)city{
  
    WeatherDataRequest *TemperatureLineData = [[WeatherDataRequest alloc]init];
    [self.titleArray removeAllObjects];
    [self.textArray removeAllObjects];
    [TemperatureLineData getData:^{
        //给折线图赋值
        if ([TemperatureLineData.error isEqualToString:@"1"]) {
            [self AlertController:@"网络错误！\n暂无城市信息"];
        }else {
        [[NSUserDefaults standardUserDefaults] setObject:city forKey:@"city"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        self.DataDic = TemperatureLineData.LifeIndex;
        self.AQIDic = TemperatureLineData.pm;
        for (NSArray *arrays in  [self.DataDic allValues]) {
            [self.titleArray addObject:arrays[0]];
            [self.textArray addObject:arrays[1]];
        }
        [self initDataSource];
        }
    } withcity:city];
}

#pragma mark - 定位

- (void)initLocationDataSource {
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 1000.0f;
    [self.locationManager startUpdatingLocation];
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [self.locationManager requestAlwaysAuthorization];//for iOS 8
    }
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *currentLocation = [locations lastObject];
    CLLocationCoordinate2D coor = currentLocation.coordinate;
    NSLog(@"%f",coor.latitude);//获取经度
    NSLog(@"%f",coor.longitude);//获取纬度
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             _locationCity = [[NSUserDefaults standardUserDefaults]objectForKey:@"locationCity"];
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取城市
             NSDictionary *addressDic= placemark.addressDictionary;
             NSString *city = placemark.locality;
             NSLog(@"%@",placemark.subLocality);//输出所在的区
             NSLog(@"%@",placemark.country);//输出所在国家
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
                 
             }
         [[NSUserDefaults standardUserDefaults] setObject:city forKey:@"locationCity"];
         [[NSUserDefaults standardUserDefaults]synchronize];
             
          NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
          NSArray* languages = [defs objectForKey:@"AppleLanguages"];
          NSString* preferredLang = [languages objectAtIndex:0];
             _language = [[NSUserDefaults standardUserDefaults]boolForKey:@"language"];
             _isFristLoca = [[NSUserDefaults standardUserDefaults]boolForKey:@"isFristLoca"];
             if ([preferredLang isEqualToString:@"zh-Hans-US"]) {
                   if (city.length < 5) {
                   
                       city = [city substringToIndex:city.length - 1];
                   }
                 if (![_locationCity isEqualToString:city]) {
                     _isFristLoca = NO;
                 }
                 if (!_isFristLoca) {
                     if (![city isEqualToString:_city]) {
                         [self Alert:[NSString stringWithFormat:@"您当前的城市为：%@\n是否切换为该城市？",city] cityName:city];
                         [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"isFristLoca"];
                         [[NSUserDefaults standardUserDefaults]synchronize];
                         }
                  }
                }else {
                if (!_language) {
                   [self AlertController:@"您的设备语言不支持定位，请手动选择"];
                   [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"language"];
                   [[NSUserDefaults standardUserDefaults]synchronize];
                }
            }
             
          }else if (error == nil && [array count] == 0)
         {
             [self AlertController:@"当前城市不支持定位,请手动选择！"];
             NSLog(@"No results were returned.");

         }else if (error != nil)
         {
             [self AlertController:@"定位失败,请手动选择！"];
             NSLog(@"An error occurred = %@", error);

         }
     }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}

- (void)AlertController:(NSString *)message {
    
    UIAlertController *prompt =  [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert] ;
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      }];
    [prompt addAction:sure];
    [self presentViewController:prompt animated:YES completion:nil];
}

- (void)Alert:(NSString *)message cityName:(NSString *)city{
    
    UIAlertController *prompt =  [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert] ;
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[NSUserDefaults standardUserDefaults] setObject:city forKey:@"city"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        _city = [[NSUserDefaults standardUserDefaults]objectForKey:@"city"];
        WeatherDataRequest *TemperatureLineData = [[WeatherDataRequest alloc]init];
        [self.titleArray removeAllObjects];
        [self.textArray removeAllObjects];
        [TemperatureLineData getData:^{
            //给折线图赋值
                self.DataDic = TemperatureLineData.LifeIndex;
                self.AQIDic = TemperatureLineData.pm;
                for (NSArray *arrays in  [self.DataDic allValues]) {
                    [self.titleArray addObject:arrays[0]];
                    NSLog(@"%@",self.titleArray);
                    [self.textArray addObject:arrays[1]];
                }
                [self initDataSource];
        } withcity:city];

        [self.lineChart InitDataSource:city];
        [self.weatherView httpRequst:city];
        
    
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
    [prompt addAction:sure];
    [prompt addAction:cancel];
    [self presentViewController:prompt animated:YES completion:nil];
}


- (void)tableViewAnimation{
    [UIView animateWithDuration:0.3 animations:^{
        
        self.tableView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 * 2 - 40, SCREEN_WIDTH, SCREEN_HEIGHT / 3 *2);
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:1
                              delay:0
             usingSpringWithDamping:0.3
              initialSpringVelocity:0.8
                            options:0
                         animations:^{
                             self.tableView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 * 2 , SCREEN_WIDTH, SCREEN_HEIGHT / 3 *2);
                             
                         }
                         completion:nil];
    }];



}
+ (NSString *)getLanguageCode
{
    return [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode];
}
@end
